package com.itheima.mm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mm.constant.JwtClaimsConstant;
import com.itheima.mm.dto.CourseDTO;
import com.itheima.mm.entity.CoursePageQueryParams;
import com.itheima.mm.entity.PageResult;
import com.itheima.mm.entity.QueryPageBean;
import com.itheima.mm.exception.BaseException;
import com.itheima.mm.mapper.CatalogMapper;
import com.itheima.mm.mapper.CourseMapper;
import com.itheima.mm.mapper.TagMapper;
import com.itheima.mm.pojo.Catalog;
import com.itheima.mm.pojo.Course;
import com.itheima.mm.pojo.Tag;
import com.itheima.mm.properties.JwtProperties;
import com.itheima.mm.service.CourseService;
import com.itheima.mm.utils.DateUtils;
import com.itheima.mm.utils.JwtUtil;
import com.itheima.mm.vo.CourseAllVO;
import com.itheima.mm.vo.CourseVO;
import io.jsonwebtoken.Claims;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description CourseServiceImpl
 * @Author xiao
 * @Date 2024-06-22
 */

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public void add(CourseDTO courseDTO) {
        //将courseDTO转化为course对象
        Course course = new Course();
        BeanUtils.copyProperties(courseDTO,course);


        course.setCreateDate(DateUtils.parseDate2String(new Date()));



        String token = request.getHeader(jwtProperties.getAdminTokenName());



        if(StringUtils.isNotEmpty(token)){
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(),token);
            Integer userId = Integer.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            course.setUserId(userId);
        }

        courseMapper.insert(course);

    };

   //实现分页，展示数据列表
    @Override
    public PageResult<CourseVO> findListByPage(
            QueryPageBean<CoursePageQueryParams> queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        CoursePageQueryParams queryParams  = queryPageBean.getQueryParams();
        //queryPageBean 主对象（包括第几页，这一页有几张，以及筛选条件）
        //queryParams  子对象  （筛选条件信息）

        Long total = courseMapper.countByCondition(queryParams);

        Integer start = (currentPage-1)*pageSize;
        Integer length = pageSize;
        List<CourseVO> courseVOList = courseMapper.findByConditon(start,length,queryParams);


        PageResult<CourseVO> pageResult = new PageResult<>(total,courseVOList);
        //有参构造函数，为属性赋值
        return pageResult;
    }



    //使用PageHelper插件实现分页操作，展示数据列表
    @Override
    public PageResult<CourseVO> findListByPage2(
            QueryPageBean<CoursePageQueryParams> queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        CoursePageQueryParams queryParams  = queryPageBean.getQueryParams();
        //queryPageBean 主对象（包括第几页，这一页有几张，以及筛选条件）
        //queryParams  子对象  （筛选条件信息）


        PageHelper.startPage(currentPage,pageSize);

        Page<CourseVO> page = courseMapper.findByConditon2(queryParams);

        Long total = page.getTotal();
        List<CourseVO> courseVOList = page.getResult();


        PageResult<CourseVO> pageResult = new PageResult<>(total,courseVOList);
        return pageResult;



    }

    //更新学科方法
    @Override
    public void update(CourseDTO courseDTO) {
          Course course = new Course();
          BeanUtils.copyProperties(courseDTO,course);

          courseMapper.update(course);

    };

    //删除学科


    @Override
    public void delete(Integer courseId) {
        CourseVO courseVO = courseMapper.findById(courseId);

        if(courseVO.getCatalogQty()>0 || courseVO.getQuestionQty()>0 || courseVO.getTagQty()>0){
            throw new BaseException("学科有关联数据，无法删除");
        }


        courseMapper.deleteById(courseId);
    };



    @Autowired
    private CatalogMapper catalogMapper;


    @Autowired
    private TagMapper tagMapper;

    //含全部学科（标签、目录列表）列表
    @Override
    public List<CourseAllVO> findListAll() {
        //获取全部学科
        List<Course> courseList = courseMapper.findListAll();

        List<CourseAllVO> courseAllVOList = courseList.stream().map(course ->{
            CourseAllVO courseAllVO = new CourseAllVO();
            BeanUtils.copyProperties(course,courseAllVO);
            //根据学科id 查询并赋值目录列表
            List<Catalog> catalogList = catalogMapper.findListByCourseId(course.getId());

            //根据学科id 查询并赋值标签列表
            List<Tag> tagList = tagMapper.findListByCourseId(course.getId());

            courseAllVO.setCatalogList(catalogList);

            courseAllVO.setTagList(tagList);

            return courseAllVO;

        }).collect(Collectors.toList());



        return courseAllVOList;
    }
}
